package com.habdqn.studentmanager.interceptor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.habdqn.studentmanager.constant.Constant;
import com.habdqn.studentmanager.service.SystemService;
import com.habdqn.studentmanager.util.ProjectUtil;

/**
 * @author Administrator 登陆拦截 2017年5月15日
 * 
 */
public class LoginInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
	
	@Resource
	SystemService systemService;
	
	/**
	 * 登陆地址(不带项目名) <br/>
	 * /login
	 */
	private String loginUrl;

	/**
	 * 忽略的urls
	 */
	private List<String> excludeUrls;

	public List<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	/**
	 * Handle执行之前调用这个方法
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
	        throws Exception {
		String url = request.getServletPath();
		
		logger.debug("被拦截的地址 {}", url);
		
		// 判断是否是登录页
		if (loginUrl.equals(url)) {
			logger.debug("是登录页");
			return true;
		}
		
		// 判断是否在过滤列表中
		for (String u : excludeUrls) {
			if (u.equals(url)) {
				logger.debug("{} 在过滤列表中", url);
				return true;
			}
		}
		
		// 在线检测
		Object user = ProjectUtil.getSessionAttr(Constant.CURRENT_TEACHER);
		
		if (null != user) {
			logger.debug("当前在线");
			return true;
		}
		
		String token = ProjectUtil.getCookie(Constant.TOKEN);
		
		// 校验token
		if (StringUtils.isNotEmpty(token)) {
			try {
				systemService.login(token);		
				logger.debug("通过Cookie登录");
				return true;
			}
			catch (RuntimeException e) {
				logger.debug("通过Cookie登录失败", e);
			}
		}
		
		logger.debug("没有登录信息, 跳转至 {}", loginUrl);
		// 重定向到登陆页面
		response.sendRedirect(ProjectUtil.getContextPath() + loginUrl);
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
	        ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
	        throws Exception {
		
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

}
